# -*- coding: utf-8 -*-

import logging
import json
from urllib import quote

from odoo import http
from odoo.http import request
from odoo.addons.web.controllers.main import serialize_exception

_logger = logging.getLogger(__name__)

    
class TestPrint(http.Controller):
    @http.route('/web/testprint', type='http', auth="none")
    @serialize_exception
    def test_print(self):
        request.session.authenticate(request.session.db, 'worker', 'worker')
        context = {
            'session_info': json.dumps(request.env['ir.http'].session_info())
        }
        context = request.env['ir.http'].webclient_rendering_context()
        return http.request.render('lmch_buliao.worker', qcontext=context)


class ExportExcel(http.Controller):
    @http.route('/buliao/month_bill', type='http', auth='user')
    @serialize_exception
    def export_month_bill(self, query, token):
        query = json.loads(query)
        partner = request.env['res.partner'].browse(query['partner_id'])
        start_month = query['start_month']
        end_month = query['end_month']
        if end_month < start_month:
            start_month, end_month = end_month, start_month
        excel_name = '%s%s年%s月份到%s月份对账单.xls' % \
                     (partner.name.encode('utf8'), query['year'], start_month, end_month)
        excel_name = quote(excel_name)
        response = request.make_response(None,
                                         headers=[('Content-Type', 'application/vnd.ms-excel'),
                                                  ('Content-Disposition',
                                                   'attachment; filename=%s;' % excel_name)],
                                         cookies={'fileToken': token})
        request.env['buliao.partner.month.bill.wiz'].export_month_bill(query, response.stream)
        return response

